<template>
  <div class="component-business-info-edit">
    <!-- 工商信息 -->
    <div class="business-info">
      <el-form
        ref="companyInfoFormRef"
        :model="companyInfoForm"
        :rules="companyInfoRule"
        label-width="140px"
        @submit.prevent
      >
        <div class="business-info-wrapper">
          <div class="business-info-left">
            <el-form-item
              :label="$t('product.licenseNumber')+':'"
              prop="creditCode"
            >
              <el-input
                v-model.trim="companyInfoForm.creditCode"
                maxlength="20"
                :placeholder="$t('product.licenseNumber')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('product.EnterpriseName')+':'"
              prop="firmName"
            >
              <el-input
                v-model="companyInfoForm.firmName"
                maxlength="50"
                :placeholder="$t('product.firmName50Rule')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('product.EnterpriseResidence')+':'"
              prop="residence"
            >
              <el-input
                v-model="companyInfoForm.residence"
                maxlength="50"
                :placeholder="$t('product.creditCode50Rule')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('product.legalRepresentative')+':'"
              prop="representative"
            >
              <el-input
                v-model="companyInfoForm.representative"
                maxlength="20"
                :placeholder="$t('product.representative20Rule')"
              />
            </el-form-item>
            <el-form-item
              :label="$t('product.registeredCapital')+':'"
              prop="capital"
            >
              <el-input
                v-model="companyInfoForm.capital"
                style="width:200px"
                @input="changeNum"
                @keydown="channelInputLimit"
              />
              <span class="price-unit-text">万元</span>
            </el-form-item>
            <el-form-item
              :label="$t('product.establishmentAata')+':'"
              prop="foundTime"
            >
              <el-date-picker
                v-model="companyInfoForm.foundTime"
                style="width:200px"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('platform.seleData')"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item
              :label="$t('product.businessTerm')+':'"
            >
              <div style="display: flex">
                <el-date-picker
                  v-model="companyInfoForm.startTime"
                  style="width:170px;"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('date.start')"
                  clearable
                />
                <span style="margin: 0 10px">-</span>
                <span class="end-time">
                  <el-date-picker
                    ref="endTimeRef"
                    v-model="companyInfoForm.endTime"
                    :disabled="!companyInfoForm.startTime"
                    style="width:170px;"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="endTimeFlag && !companyInfoForm.endTime ? '' : $t('date.end')"
                    clearable
                    @change="endTimeFlag = false"
                    @focus="endTimeFlag = false"
                  />
                  <span
                    v-if="endTimeFlag && !companyInfoForm.endTime"
                    class="text"
                    @click="focusEndTime"
                  >
                    {{ $t('product.openEnded') }}
                  </span>
                </span>
              </div>
            </el-form-item>
            <el-form-item
              :label="$t('product.businessScope')+':'"
              prop="businessScope"
              style="margin-bottom:30px;"
            >
              <el-input
                v-model="companyInfoForm.businessScope"
                type="textarea"
                resize="none"
                :rows="4"
                :placeholder="$t('product.businessScope500Rule')"
                maxlength="500"
              />
            </el-form-item>
          </div>
          <div class="business-info-right">
            <el-form-item
              :label="$t('product.businessLicense')+':'"
              prop="businessLicense"
            >
              <div class="business-license-box">
                <div class="license-content">
                  <img-upload
                    v-model="companyInfoForm.businessLicense"
                    :limit="1"
                  />
                  <div class="example-box">
                    <img
                      src="@/assets/example-img/Business-license.png"
                      alt
                    >
                    <div class="tips">
                      示例
                    </div>
                  </div>
                </div>
                <div class="upload-tips">
                  仅限jpg、gif、png，仅限上传1张
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="footer">
      <div class="foot-box">
        <div
          v-permission="['shop:shopCompany:save']"
          class="btn primary"
          style="margin-left:152px"
          @click="validationCompanyInfoForm"
        >
          {{ $t('shop.submitChanges') }}
        </div>
      </div>
    </div>
    <!-- /工商信息 -->
  </div>
</template>

<script setup>
import { validNoEmptySpace } from '@/utils/validate.js'
import { Debounce } from '@/utils/debounce.js'
import { ElMessage } from 'element-plus'
import moment from 'moment'

const emit = defineEmits(['successUpdate'])

// 店铺工商信息
const companyInfoForm = reactive({
  creditCode: '',
  firmName: '',
  residence: '',
  representative: '',
  capital: '',
  foundTime: '',
  startTime: '',
  endTime: '',
  businessScope: '',
  businessLicense: ''
})
const endTimeFlag = ref(true)

/**
 * 成立日期：今日之前可选
 */
const pickerOptions = reactive({
  disabledDate (time) {
    const date = moment().add(0, 'days').startOf('days')
    return (
      time.getTime() >= date.valueOf()
    )
  }
})

// eslint-disable-next-line no-unused-vars
const validRepresentative = (rule, value, callback) => {
  companyInfoForm.representative = companyInfoForm.representative.trim()
  if (companyInfoForm.representative.indexOf(' ') !== -1) {
    callback(new Error('法定代表人不能有空格'))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validbusinessScope = (rule, value, callback) => {
  if (!value || !value.trim()) {
    companyInfoForm.businessScope = ''
    callback(new Error($t('multishop.shopInformation.businessScopeEmpty')))
  } else {
    callback()
  }
}

/**
 * 纯空格校验
 */
// eslint-disable-next-line no-unused-vars
const validEmptySpace = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('multishop.shopInformation.EmptyTips')))
  } else {
    callback()
  }
}

const companyInfoRule = reactive({
  creditCode: [
    { required: true, message: $t('product.creditCodeRule'), trigger: 'blur' }
  ],
  firmName: [
    { required: true, message: $t('product.firmNameRule'), trigger: 'blur' }
  ],
  residence: [
    { required: true, message: $t('product.residenceRule'), trigger: 'blur' },
    // 住所，校验纯空格
    { validator: validEmptySpace, trigger: 'blur' }
  ],
  businessScope: [
    { required: true, message: $t('product.businessScopeRule'), trigger: 'blur' },
    { validator: validbusinessScope, trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: $t('product.businessLicenseRule'), trigger: 'change' }
  ],
  representative: [
    { required: true, message: $t('product.representativeRule'), trigger: 'blur' },
    { validator: validRepresentative, trigger: 'blur' }
  ],
  capital: [
    { required: true, message: $t('product.capitalRule'), trigger: 'blur' }
  ],
  foundTime: [
    { required: true, message: $t('product.foundTimeRule'), trigger: 'change' }
  ]
})

/**
 * 查询工商信息
 */
const init = () => {
  http({
    url: http.adornUrl('/admin/shopCompany'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      Object.assign(companyInfoForm, data)
      endTimeFlag.value = true
    })
}
onMounted(() => {
  init()
})

const endTimeRef = ref('')
const focusEndTime = () => {
  endTimeRef.value?.focus()
}

/**
 * 注册资本输入框限制长度
 */
const changeNum = () => {
  if (companyInfoForm.capital < 1) {
    companyInfoForm.capital = ''
  }
  if (companyInfoForm.capital.length > 8) {
    companyInfoForm.capital = companyInfoForm.capital.slice(0, 8)
  }
}

const channelInputLimit = (e) => {
  const key = e.key
  // 不允许输入'-'
  if (key === '-' || key === '+') {
    e.returnValue = false
    return false
  }
  return true
}

/**
 * 验证工商信息
 */
const companyInfoFormRef = ref('')
const validationCompanyInfoForm = Debounce(() => {
  companyInfoFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    updateCompanyInfo()
  })
}, 1500)

/**
 * 提交工商信息审核
 */
const updateCompanyInfo = Debounce(() => {
  if (!companyInfoForm.startTime) {
    companyInfoForm.endTime = ''
  }
  http({
    url: http.adornUrl('/admin/shopCompany'),
    method: 'put',
    data: http.adornData(companyInfoForm)
  })
    .then(() => {
      ElMessage({
        message: '提交工商信息修改成功！',
        type: 'success',
        duration: 1500,
        onClose: () => {
          emit('successUpdate')
        }
      })
    })
}, 1500)
</script>

<style lang="scss" scoped>
@use "index";
</style>
